//
//  CityListViewController.m
//
//  Created by Big Watermelon on 11-11-10.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CityListViewController.h"

@interface CityListViewController ()
@property (nonatomic, retain) UIImageView* checkImgView;
- (IBAction)backToLast:(id)sender;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property NSUInteger curSection;
@property NSUInteger curRow;
@property NSUInteger defaultSelectionRow;
@property NSUInteger defaultSelectionSection;
@end

@implementation CityListViewController
@synthesize tbView;

#define CHECK_TAG 1110

@synthesize cities, keys, checkImgView, curSection, curRow, delegate;
@synthesize defaultSelectionRow, defaultSelectionSection;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self                            = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    curRow = NSNotFound;
    self.tbView.delegate = self;
    self.tbView.dataSource = self;
    self.searchBar.delegate = self;
    self.checkImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"check"]];
    checkImgView.tag = CHECK_TAG;
    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict" ofType:@"plist"];
    self.cities = [[NSDictionary alloc]initWithContentsOfFile:path];

    self.keys = [[cities allKeys] sortedArrayUsingSelector:@selector(compare:)];


    //get default selection from delegate
    NSString* defaultCity           = [delegate getDefaultCity];
    if (defaultCity) {
        NSArray *citySection;
    self.defaultSelectionRow        = NSNotFound;
        //set table index to this city if it existed
        for (NSString* key in keys) {
    citySection                     = [cities objectForKey:key];
    self.defaultSelectionRow        = [citySection indexOfObject:defaultCity];
            if (NSNotFound == defaultSelectionRow)
                continue;
            //found match recoard position
    self.defaultSelectionSection    = [keys indexOfObject:key];
            break;
        }

        if (NSNotFound != defaultSelectionRow) {

    self.curSection                 = defaultSelectionSection;
    self.curRow                     = defaultSelectionRow;
    NSIndexPath *indexPath          = [NSIndexPath indexPathForRow:defaultSelectionRow inSection:defaultSelectionSection];
            [self.tbView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

        }
    }
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    NSEnumerator *enumerator = [cities objectEnumerator];
    NSMutableArray *citiesArry = [[NSMutableArray alloc]init];
    if ([enumerator  isEqual:searchString]) {
        [citiesArry addObject:self.keys];
    }
    keys = citiesArry;
    [self.tbView reloadData];
    return YES;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.keys                       = nil;
    self.cities                     = nil;
    self.checkImgView               = nil;
    self.tbView                     = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [keys count];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSString *key                   = [keys objectAtIndex:section];
    NSArray *citySection            = [cities objectForKey:key];
    return [citySection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    NSString *key = [keys objectAtIndex:indexPath.section];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    } else {

    }

    // Configure the cell...
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    cell.textLabel.text = [[cities objectForKey:key] objectAtIndex:indexPath.row];

    if (indexPath.section == curSection && indexPath.row == curRow)
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    else
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *key = [keys objectAtIndex:section];
    return key;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return keys;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
       //clear previous
    NSIndexPath *prevIndexPath      = [NSIndexPath indexPathForRow:curRow inSection:curSection];
    UITableViewCell* cell           = [tableView cellForRowAtIndexPath:prevIndexPath];
    cell.accessoryType              = UITableViewCellAccessoryNone;

    curSection                      = indexPath.section;
    curRow                          = indexPath.row;

    //add new check mark
    cell                            = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType              = UITableViewCellAccessoryCheckmark;

    //    if (curRow != NSNotFound) {
    NSString* key                   = [keys objectAtIndex:curSection];
    [delegate citySelectionUpdate:[[cities objectForKey:key] objectAtIndex:curRow]];
    //    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)backToLast:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
